/**
 * Copyright &copy; 2012-2014 <a href="https://github.com/thinkgem/jeesite">JeeSite</a> All rights reserved.
 */
package cn.knet.sp.ncrm.modules.sys.security.cas;

import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.Permission;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.cas.CasAuthenticationException;
import org.apache.shiro.cas.CasRealm;
import org.apache.shiro.cas.CasToken;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.PrincipalCollection;
//import org.jasig.cas.client.authentication.AttributePrincipal;
//import org.jasig.cas.client.validation.Assertion;
//import org.jasig.cas.client.validation.TicketValidationException;
//import org.jasig.cas.client.validation.TicketValidator;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.io.Serializable;
import java.util.Collection;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

//import cn.knet.agent.webservice.CommonUserService;
import cn.knet.sp.ncrm.common.config.Global;
import cn.knet.sp.ncrm.common.utils.SpringContextHolder;
import cn.knet.sp.ncrm.common.web.Servlets;
import cn.knet.sp.ncrm.modules.sys.menu.entity.Menu;
import cn.knet.sp.ncrm.modules.sys.role.entity.Role;
import cn.knet.sp.ncrm.modules.sys.user.entity.User;
import cn.knet.sp.ncrm.modules.sys.user.service.SystemService;
import cn.knet.sp.ncrm.modules.sys.utils.LogUtils;
import cn.knet.sp.ncrm.modules.sys.utils.UserUtils;

/**
 * 系统安全认证实现类
 *
 * @author ThinkGem
 * @version 2014-7-5
 */
@Service
//@DependsOn({"userDao","roleDao","menuDao"})
public class SystemCasAuthorizingRealm extends CasRealm {

	private Logger logger = LoggerFactory.getLogger(getClass());

	private SystemService systemService;

//	@Resource
//	private CommonUserService commonUserService;

	// 系统的唯一标记，用来查询用户在特定系统下的角色信息
	@Value("${app.systemTag}")
	private String systemTag;
/*
	private TicketValidator ticketValidator;


	public TicketValidator getTicketValidator() {
		return ticketValidator;
	}

	public void setTicketValidator(TicketValidator ticketValidator) {
		this.ticketValidator = ticketValidator;
	}

	@Override
	protected TicketValidator createTicketValidator() {
		return this.ticketValidator;
	}

*/
	/**
	 * 认证回调函数, 登录时调用
	 */
	@Override
	@SuppressWarnings("unchecked")
	protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
		/*
		CasToken casToken = (CasToken) token;
		if (token == null) {
			return null;
		}

		String ticket = (String) casToken.getCredentials();
		if (!org.apache.shiro.util.StringUtils.hasText(ticket)) {
			return null;
		}

		TicketValidator ticketValidator = ensureTicketValidator();

		try {
			// contact CAS server to validate service ticket
			Assertion casAssertion = ticketValidator.validate(ticket, getCasService());
			// get principal, user id and attributes
			AttributePrincipal casPrincipal = casAssertion.getPrincipal();
			String userId = casPrincipal.getName();
			logger.debug("Validate ticket : {} in CAS server : {} to retrieve user : {}", new Object[]{
					ticket, getCasServerUrlPrefix(), userId
			});

			Map<String, Object> attributes = casPrincipal.getAttributes();
			// refresh authentication token (user id + remember me)
			casToken.setUserId(userId);
			String rememberMeAttributeName = getRememberMeAttributeName();
			String rememberMeStringValue = (String) attributes.get(rememberMeAttributeName);
			boolean isRemembered = rememberMeStringValue != null && Boolean.parseBoolean(rememberMeStringValue);
			if (isRemembered) {
				casToken.setRememberMe(true);
			}
			// create simple authentication info

			Principal principal = new Principal(userId);
			return new SimpleAuthenticationInfo(principal, ticket, this.getName());

			// 校验用户名密码
//			User user = getSystemService().getUserByLoginName(userId);
//			if (user != null) {
//				if (Global.NO.equals(user.getLoginFlag())){
//					throw new AuthenticationException("msg:该已帐号禁止登录.");
//				}
//				byte[] salt = Encodes.decodeHex(user.getPassword().substring(0, 16));
//				return new SimpleAuthenticationInfo(new Principal(user), ticket, this.getName());
//			} else {
//				return null;
//			}
		} catch (TicketValidationException e) {
			throw new CasAuthenticationException("Unable to validate ticket [" + ticket + "]", e);
		}
		*/
		return null;
	}

	/**
	 * 授权查询回调函数, 进行鉴权但缓存中无用户的授权信息时调用
	 */
	@Override
//	protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
//		SimplePrincipalCollection principalCollection = (SimplePrincipalCollection) principals;
//		List<Object> listPrincipals = principalCollection.asList();
//		Principal principal = (Principal) listPrincipals.get(0);
//		// 获取当前已登录的用户
//		if (!Global.TRUE.equals(Global.getConfig("user.multiAccountLogin"))) {
//			Collection<Session>
//					sessions =
//					getSystemService().getSessionDao()
//							.getActiveSessions(true, principal.getLoginName(), UserUtils.getSession());
//			if (sessions.size() > 0) {
//				// 如果是登录进来的，则踢出已在线用户
//				if (UserUtils.getSubject().isAuthenticated()) {
//					for (Session session : sessions) {
//						getSystemService().getSessionDao().delete(session);
//					}
//				}
//				// 记住我进来的，并且当前用户已登录，则退出当前用户提示信息。
//				else {
//					UserUtils.getSubject().logout();
//					throw new AuthenticationException("msg:账号已在其它地方登录，请重新登录。");
//				}
//			}
//		}
//		UserAccount userAccount = this.commonUserService.getUserAccount(principal.getLoginName());
//
//		if (userAccount != null && !userAccount.isLocked()) {
//
//			SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
//			List<String> roles = this.commonUserService.getUserRolesName(principal.getLoginName(), this.systemTag);
//			if (roles != null) {// 新增角色
//				info.addRoles(roles);
//			}
//			List<String>
//					permissionStrings =
//					this.commonUserService.getPermissionByLoginId(principal.getLoginName(), this.systemTag);
//
//			if (permissionStrings != null) {
//				for (String permissionString : permissionStrings) {
//					Permission
//							permission =
//							new WildcardPermission(StringUtils.replace(permissionString, "/", ":"));
//					info.addObjectPermission(permission);
//				}
//			}
//
//			// 记录登录日志
////			LogUtils.saveLog(Servlets.getRequest(), "系统登录");
//			return info;
//		} else {
//			return null;
//		}
//	}

	protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
		/*
		Principal principal = (Principal) getAvailablePrincipal(principals);
		List<String> roles = commonUserService.getUserRolesName(principal.getLoginName(),Global.getConfig("app.systemTag"));
		if(roles == null || !roles.contains(Global.getConfig("ncrm.role"))) {
			throw new AuthenticationException("msg:没有该系统登陆权限，请联系管理员。");
		}
		// 获取当前已登录的用户
		if (!Global.TRUE.equals(Global.getConfig("user.multiAccountLogin"))){
			Collection<Session> sessions = getSystemService().getSessionDao().getActiveSessions(true, principal, UserUtils.getSession());
			if (sessions.size() > 0){
				// 如果是登录进来的，则踢出已在线用户
				if (UserUtils.getSubject().isAuthenticated()){
					for (Session session : sessions){
						getSystemService().getSessionDao().delete(session);
					}
				}
				// 记住我进来的，并且当前用户已登录，则退出当前用户提示信息。
				else{
					UserUtils.getSubject().logout();
					throw new AuthenticationException("msg:账号已在其它地方登录，请重新登录。");
				}
			}
		}
		User user = getSystemService().getUserByLoginName(principal.getLoginName(),true);
		if (user != null) {
			SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
			List<Menu> list = UserUtils.getMenuList();
			for (Menu menu : list){
				if (org.apache.commons.lang3.StringUtils.isNotBlank(menu.getPermission())){
					// 添加基于Permission的权限信息
					for (String permission : org.apache.commons.lang3.StringUtils.split(menu.getPermission(), ",")){
						info.addStringPermission(permission);
					}
				}
			}
			// 添加用户权限
			info.addStringPermission("user");
			// 添加用户角色信息
			for (Role role : user.getRoleList()){
				info.addRole(role.getEnname());
			}
			// 更新登录IP和时间
			getSystemService().updateUserLoginInfo(user);
			// 记录登录日志
			LogUtils.saveLog(Servlets.getRequest(), "系统登录");
			return info;
		} else {
			//crm系统用户不存在也是无授权访问页面
			return null;
		}
		*/
		return null;
	}

	@Override
	protected void checkPermission(Permission permission, AuthorizationInfo info) {
		authorizationValidate(permission);
		super.checkPermission(permission, info);
	}

	@Override
	protected boolean[] isPermitted(List<Permission> permissions, AuthorizationInfo info) {
		if (permissions != null && !permissions.isEmpty()) {
			for (Permission permission : permissions) {
				authorizationValidate(permission);
			}
		}
		return super.isPermitted(permissions, info);
	}

	@Override
	public boolean isPermitted(PrincipalCollection principals, Permission permission) {
		return super.isPermitted(principals, permission);
	}

	@Override
	protected boolean isPermittedAll(Collection<Permission> permissions, AuthorizationInfo info) {
		if (permissions != null && !permissions.isEmpty()) {
			for (Permission permission : permissions) {
				authorizationValidate(permission);
			}
		}
		return super.isPermittedAll(permissions, info);
	}

	/**
	 * 授权验证方法
	 */
	private void authorizationValidate(Permission permission) {
		// 模块授权预留接口
	}

//	/**
//	 * 清空用户关联权限认证，待下次使用时重新加载
//	 */
//	public void clearCachedAuthorizationInfo(Principal principal) {
//		SimplePrincipalCollection principals = new SimplePrincipalCollection(principal, getName());
//		clearCachedAuthorizationInfo(principals);
//	}

	/**
	 * 清空所有关联认证
	 *
	 * @Deprecated 不需要清空，授权缓存保存到session中
	 */
	@Deprecated
	public void clearAllCachedAuthorizationInfo() {
//		Cache<Object, AuthorizationInfo> cache = getAuthorizationCache();
//		if (cache != null) {
//			for (Object key : cache.keys()) {
//				cache.remove(key);
//			}
//		}
	}

	/**
	 * 获取系统业务对象
	 */
	public SystemService getSystemService() {
		if (systemService == null) {
			systemService = SpringContextHolder.getBean(SystemService.class);
		}
		return systemService;
	}


	/**
	 * 授权用户信息
	 */
	public static class Principal implements Serializable {

		private static final long serialVersionUID = 1L;

		private String id; // 编号
		private String loginName; // 登录名
		private String name; // 姓名

		public Principal(String loginName) {

			this.loginName = loginName;
		}

		public Principal(User user) {
			this.id = user.getId();
			this.loginName = user.getLoginName();
			this.name = user.getName();
		}

		public String getLoginName() {
			return loginName;
		}

//		@JsonIgnore
//		public Map<String, Object> getCacheMap() {
//			if (cacheMap==null){
//				cacheMap = new HashMap<String, Object>();
//			}
//			return cacheMap;
//		}

		/**
		 * 获取SESSIONID
		 */
		public String getSessionid() {
			try {
				return (String) UserUtils.getSession().getId();
			} catch (Exception e) {
				return "";
			}
		}

		public String getId() {
			return id;
		}

		public void setId(String id) {
			this.id = id;
		}

		public void setLoginName(String loginName) {
			this.loginName = loginName;
		}

		public String getName() {
			return name;
		}

		public void setName(String name) {
			this.name = name;
		}
	}



}
